<template>
  <div class="materialThreshold zy-content">
    <!-- 搜索区域 - 调整为与materialMoldCode页面一致的样式 -->
    <div class="search clear">
      <div class="search-box-layout">
        <Row :gutter="24">
          <Col span="6">
          <p class="label">物料编码</p>
          <div class="ipt">
            <Input v-model="searchParams.materialCode" placeholder="请输入物料编码" clearable />
          </div>
          </Col>
          <Col span="6">
          <p class="label">物料名称</p>
          <div class="ipt">
            <Input v-model="searchParams.materialName" placeholder="请输入物料名称" clearable />
          </div>
          </Col>
          <Col span="6">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button type="primary" class="search-btn" @click="handleSearch">搜索</Button>
              <Button class="reset-btn" @click="resetSearch">重置</Button>
            </div>
          </div>
          </Col>
        </Row>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>
        <Button @click="showAddModal" style="color: #fff!important;">新增</Button>
      </div>

      <!-- 表格区域 -->
      <div class="tableContent">
        <Table class="resizable-table" border :columns="columns" ellipsis ref="selection" stripe :data="tableData"
          @on-selection-change="onSelectChange">
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="editRow(row)"><i class="iconfont zy-common-bianji"></i>编辑</span>
            <span class="operationBtn" @click="delRow(row)"><i class="iconfont zy-common-shanchu"></i>{{
              $t('common.Delete')
            }}</span>
          </template>
        </Table>
      </div>

      <!-- 分页 -->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectedIds.length" />
        <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
          @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
      </div>
    </div>

    <Modal v-model="modalVisible" :title="modalTitle" width="800" @on-cancel="resetForm">
      <Form ref="form" :model="formData" :label-width="120">
        <Row :gutter="16">
          <Col span="24">
          <FormItem label="物料" prop="materialId">
            <Select v-model="formData.materialId" filterable clearable remote :remote-method="handleMaterialRemote"
              :loading="materialLoading" placeholder="请输入物料编码或名称搜索" style="width: 100%;">
              <Option v-for="mat in materialList" :key="mat.id" :value="mat.id">{{ mat.materialCode }} - {{ mat.materialName }}</Option>
            </Select>
            <div v-if="errors.materialId" class="error-tip">{{ errors.materialId }}</div>
          </FormItem>
          </Col>

          <Col span="24">
          <FormItem label="阈值数量" prop="thresholdQuantity">
            <InputNumber v-model="formData.thresholdQuantity" placeholder="请输入阈值数量" :min="0" style="width: 100%;" />
            <div v-if="errors.thresholdQuantity" class="error-tip">{{ errors.thresholdQuantity }}</div>
          </FormItem>
          </Col>
        </Row>
      </Form>

      <div slot="footer">
        <Button @click="modalVisible = false">{{ $t("common.Cancel") }}</Button>
        <Button type="primary" @click="submitForm" :loading="submitLoading">
          确认
        </Button>
      </div>
    </Modal>

    <!-- 删除确认弹框 -->
    <Modal :mask-closable="false" v-model="deleteShow" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.sureDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="deleteSure">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: "materialThreshold",
  data() {
    return {
      materialList: [],
      materialLoading: false,
      deleteShow: false,
      currentDeleteId: null,
      // 搜索相关
      searchParams: {
        materialCode: '',
        materialName: ''
      },

      // 表格相关
      columns: [
        { type: "selection", width: 60, align: "center" },
        { title: "物料编码", key: "materialCode", minWidth: 150, align: "center" },
        { title: "物料名称", key: "materialName", minWidth: 150, align: "center" },
        { title: "阈值数量", key: "thresholdQuantity", minWidth: 120, align: "center" },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 200,
          align: "center"
        }
      ],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pageSizeOption: [10, 20, 30, 50],
      selectedIds: [],

      // 表单相关
      modalVisible: false,
      modalTitle: "新增物料阈值配置",
      submitLoading: false,
      isEdit: false,
      currentId: null,
      errors: {},
      formData: {
        id: null,
        materialId: null,
        thresholdQuantity: null
      },
    };
  },

  mounted() {
    this.getList();
  },

  methods: {
    // 搜索物料
    handleMaterialRemote(query) {
      this.materialLoading = true;
      return this.axios({
        method: 'POST',
        url: '/dms/material/page',
        data: {
          materiallName: query,
          pageNum: 1,
          pageSize: 20
        }
      }).then(res => {
        if (res.code === 200) {
          this.materialList = res.data.records || [];
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true });
        }
      }).finally(() => {
        this.materialLoading = false;
      });
    },

    // 获取列表数据
    getList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        materialCode: this.searchParams.materialCode,
        materialName: this.searchParams.materialName
      };

      this.axios({
        method: "POST",
        url: "/dms/supply/marketing/balance/material/config/page",
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list || [];
          this.total = res.data.total || 0;
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true });
        }
      }).catch(error => {
        console.error('获取列表数据失败:', error);
        this.$Message.error('获取列表数据失败');
      });
    },

    // 搜索
    handleSearch() {
      this.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetSearch() {
      this.searchParams = {
        materialCode: '',
        materialName: ''
      };
      this.handleSearch();
    },

    // 显示新增模态框
    showAddModal() {
      this.modalTitle = "新增物料阈值配置";
      this.isEdit = false;
      this.currentId = null;
      this.resetForm();
      this.modalVisible = true;
    },

    // 编辑行
    async editRow(row) {
      this.modalTitle = "编辑物料阈值配置";
      this.isEdit = true;
      this.currentId = row.id;
      this.resetForm();
      
      // 使用物料名称查询物料列表，确保能显示已选物料
      if (row.materialName) {
        await this.handleMaterialRemote(row.materialName);
      }
      
      // 设置表单数据
      this.formData = {
        id: row.id,
        materialId: row.materialId,
        thresholdQuantity: row.thresholdQuantity
      };
      
      this.modalVisible = true;
    },

    // 验证表单
    validateForm() {
      this.errors = {};
      let isValid = true;

      // 验证物料
      if (!this.formData.materialId) {
        this.errors.materialId = '请选择物料';
        isValid = false;
      }

      // 验证阈值数量
      if (this.formData.thresholdQuantity === null || this.formData.thresholdQuantity === undefined || this.formData.thresholdQuantity <= 0) {
        this.errors.thresholdQuantity = '请输入有效的阈值数量（大于0）';
        isValid = false;
      }

      return isValid;
    },

    // 提交表单
    submitForm() {
      // 验证表单
      if (!this.validateForm()) {
        return;
      }

      this.submitLoading = true;

      // 提交时构造数据
      const formData = {
        materialId: this.formData.materialId,
        thresholdQuantity: this.formData.thresholdQuantity
      };

      // 编辑模式添加ID
      if (this.isEdit && this.currentId) {
        formData.id = this.currentId;
      }

      const url = this.isEdit
        ? "/dms/supply/marketing/balance/material/config/edit"
        : "/dms/supply/marketing/balance/material/config/add";

      this.axios.post(url, formData).then(res => {
        if (res.code === 200) {
          this.$Message.success(this.isEdit ? "修改成功" : "新增成功");
          this.modalVisible = false;
          this.getList();
        } else {
          this.$Message.error(res.msg || '操作失败');
        }
      }).catch(error => {
        this.$Message.error('操作失败: ' + (error.message || ''));
      }).finally(() => {
        this.submitLoading = false;
      });
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: null,
        materialId: null,
        thresholdQuantity: null
      };
      this.errors = {};
    },

    // 分页变化
    changePageNum(val) {
      this.pageNum = val;
      this.getList();
    },

    changePageSize(val) {
      this.pageSize = val;
      this.getList();
    },

    // 表格选择变化
    onSelectChange(selection) {
      this.selectedIds = selection.map(item => item.id);
    },

    // 删除确认
    deleteSure() {
      if (!this.currentDeleteId) return;

      this.axios.post('/dms/supply/marketing/balance/material/config/delete', {
        id: this.currentDeleteId
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success('删除成功');
          this.deleteShow = false;
          this.getList();
        } else {
          this.$Message.error(res.msg || '删除失败');
        }
      }).catch(error => {
        console.error('删除失败:', error);
        this.$Message.error('删除失败');
      }).finally(() => {
        this.currentDeleteId = null;
      });
    },

    // 删除行
    delRow(row) {
      this.currentDeleteId = row.id;
      this.deleteShow = true;
    }
  }
};
</script>

<style scoped lang="scss">
.materialThreshold {
  .search-area {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }

  .ivu-form-item {
    margin-bottom: 16px;
  }

  .ivu-col {
    display: flex;
    flex-direction: column;
  }

  .ivu-form-item-content {
    flex: 1;
  }

  .label {
    text-align: left !important; /* 确保label靠左对齐 */
  }

  .operationBtn {
    margin: 0 8px;  /* 增加按钮间距 */
    cursor: pointer;
    white-space: nowrap; /* 防止按钮换行 */

    &:hover {
      text-decoration: underline;
    }
  }

  .ivu-table-cell {
    padding: 12px 8px;
  }

  .error-tip {
    color: #ed4014;
    margin-top: 5px;
  }
}
</style>